package com.xander.myblog.controller;

import com.github.pagehelper.PageInfo;
import com.xander.myblog.bean.ResultBean;
import com.xander.myblog.entity.Article;
import com.xander.myblog.entity.User;
import com.xander.myblog.service.ArticleService;
import com.xander.myblog.util.ArticleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author hbxz
 * @date 2018/12/20 0020
 */
@Controller
@RequestMapping("article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @RequestMapping("addArticle")
    @ResponseBody
    public ResultBean addArticle(Article article, HttpSession session) {
        User user = (User) session.getAttribute("user");
        article.setAuthorId(user.getUserId());
        article.setCreator(user.getNickname());
        articleService.insertArticle(article);
        return new ResultBean("插入成功！");
    }
    @RequestMapping("updateArticle")
    @ResponseBody
    public ResultBean updateArticle(Article article, HttpSession session) {
        User user = (User) session.getAttribute("user");
        article.setAuthorId(user.getUserId());
        article.setCreator(user.getNickname());
        articleService.updateArticle(article);
        return new ResultBean("修改成功！");
    }

    @GetMapping("{aid}")
    public String toArticle(@PathVariable("aid") Long aid, HttpServletRequest request) {
        if(aid==null){
            return "error";
        }else{
            Article article = articleService.getArticleByAid(aid);
            if(article==null){
                return "error";
            }
            request.setAttribute("article", article);
            request.setAttribute("comments", article.getComments());
            return "article";
        }
    }
}
